package com.md.api.service.impl;

import com.md.api.common.utils.DateUtils;
import com.md.api.common.utils.IdUtil;
import com.md.api.common.utils.StringUtils;
import com.md.api.common.utils.TokenUtil;
import com.md.api.dao.*;
import com.md.api.entity.*;
import com.md.api.entity.dto.ComposeCommitDto;
import com.md.api.entity.dto.ComposeQueryDto;
import com.md.api.entity.util.Page;
import com.md.api.service.AdvertService;
import com.md.api.service.CouponService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.*;

/**
 * @Author liujie
 * @ClassName ProductServiceImpl
 **/

@Slf4j
@Service
public class CouponServiceImpl implements CouponService {



    @Resource
    TokenUtil tokenUtil;
    @Resource
    UserCouponRecordMapper userCouponMapper;
    @Resource
    CouponInfoMapper couponInfoMapper;
    @Resource
    UserPointRecordMapper pointRecordMapper;
    @Resource
    ShoppingSpuMapper spuMapper;
    @Override
    public HttpResult myCoupon(HttpServletRequest request, ComposeQueryDto qto) {
        Page page = qto.getPage();
        page.initPagingData(UserCouponRecord.class);
        String userId = tokenUtil.getUserId(request);
        List<UserCouponRecord> list = userCouponMapper.myCoupon(userId,qto.getStatus(),null);
        page.setResult(list);
        return new HttpResult(page);
    }


    @Override
    public HttpResult availableCoupon(HttpServletRequest request, ComposeCommitDto qto) {
        String userId = tokenUtil.getUserId(request);
        List<UserCouponRecord> result = new ArrayList<>();
        List<UserCouponRecord> list = userCouponMapper.availableCoupon(userId,qto.getUseWay());
        if (qto.getUseWay()==1){
            return new HttpResult(list);
        }
        Double lowerMoney = qto.getLowerMoney();
        for (UserCouponRecord couponRecord:list){
            if(couponRecord.getCouponWay()==3){
                if(null==lowerMoney){
                    lowerMoney = spuMapper.getLowerMoney(qto.getSpuIds());
                }
                if (couponRecord.getLowerMoney()<lowerMoney){
                    result.add(couponRecord);
                    continue;
                }
            }
            if (StringUtils.isEmpty(couponRecord.getShoppingSpuIds())){
                result.add(couponRecord);
            }else{
                List<String> spuIds = StringUtils.toList(couponRecord.getShoppingSpuIds());
                if (spuIds.containsAll(qto.getSpuIds())){
                    result.add(couponRecord);
                }
            }
        }
        return new HttpResult(result);
    }

    @Override
    public HttpResult redeemCoupon(HttpServletRequest request, ComposeQueryDto qto) {
        Page page = qto.getPage();
        page.initPagingData(CouponInfo.class);
        List<CouponInfo> roomList = couponInfoMapper.redeemCoupon();
        page.setResult(roomList);
        return new HttpResult(page);
    }


    @Override
    public HttpResult redeem(HttpServletRequest request, ComposeCommitDto qto) {
        String userId = tokenUtil.getUserId(request);
        CouponInfo coupon = couponInfoMapper.getByCouponId(qto.getCouponId());

        Double point = pointRecordMapper.getPoint(userId);
        if (null==point||point<coupon.getRequirePoint()) {//积分是否足够
            return HttpResult.fail("积分不足！");
        }
        BigDecimal requirePoint = new BigDecimal(new Double(coupon.getRequirePoint()).toString());
        //扣减积分记录
        List<UserPointsRecord> validRecords = pointRecordMapper.validRecords(userId);
        for (UserPointsRecord record:validRecords){
            if (requirePoint.doubleValue()==0){
                continue;
            }
            BigDecimal num3 = new BigDecimal(new Double(record.getRemainingPoint()).toString());
            if (requirePoint.subtract(num3).doubleValue()<0){//扣减足够了，反向保存剩余积分
                requirePoint = new BigDecimal("0");
                pointRecordMapper.updateRemainingPoint(record.getId(),num3.subtract(requirePoint).doubleValue(),null);
            }else{
                requirePoint = requirePoint.subtract(num3);
                pointRecordMapper.updateRemainingPoint(record.getId(),0,-1);
            }
        }

        //插入一条积分使用记录
        UserPointsRecord pointsRecord = new UserPointsRecord();
        pointsRecord.setPoint(coupon.getRequirePoint());
        pointsRecord.setRemainingPoint(0d);
        pointsRecord.setUserId(userId);
        pointsRecord.setRecordType(2);
        pointsRecord.setStatus(-1);
        pointsRecord.setRecordName("积分兑换优惠券");
        pointRecordMapper.insert(pointsRecord);


        UserCouponRecord couponRecord =new UserCouponRecord();
        String couponRecordId = IdUtil.uuid();
        couponRecord.setCouponId(coupon.getCouponId());
        couponRecord.setUserId(userId);
        couponRecord.setCouponRecordId(couponRecordId);
        couponRecord.setValidityDate(DateUtils.add(new Date(), Calendar.DATE, coupon.getValidityDay()));
        userCouponMapper.insert(couponRecord);

        return HttpResult.OK;
    }

    @Override
    public HttpResult couponPage( ComposeQueryDto qto) {
        Page page = qto.getPage();
        page.initPagingData(CouponInfo.class);
        List<CouponInfo> roomList = couponInfoMapper.selectAll(1);
        page.setResult(roomList);
        return new HttpResult(page);
    }



    @Override
    public HttpResult addCoupon(  CouponInfo couponInfo) {
        if (couponInfo.getCouponWay()==1&&(couponInfo.getDiscount()>1||couponInfo.getDiscount()<=0)){
            return HttpResult.fail("折扣值请输入0-1之前的数字");
        }
        if (couponInfo.getCouponWay()==3&&(couponInfo.getDiscount()>couponInfo.getLowerMoney())){
            return HttpResult.fail("满减金额不能小于优惠金额");
        }
        String couponId = UUID.randomUUID().toString().replaceAll("-", "").toLowerCase();
        couponInfo.setCouponId(couponId);
        couponInfoMapper.insert(couponInfo);
        return HttpResult.OK;
    }

    @Override
    public HttpResult deleteCoupon(  CouponInfo couponInfo) {

        List<UserCouponRecord> list= userCouponMapper.getValidByCouponId(couponInfo.getCouponId());

        if (!CollectionUtils.isEmpty(list)){
            return HttpResult.fail("该优惠券存在用户未使用记录，不可删除");
        }

        couponInfoMapper.delete(couponInfo.getCouponId());
        return HttpResult.OK;
    }

    @Override
    public HttpResult updateCoupon(  CouponInfo couponInfo) {
        if (couponInfo.getCouponWay()==1&&(couponInfo.getDiscount()>1||couponInfo.getDiscount()<=0)){
            return HttpResult.fail("折扣值请输入0-1之前的数字");
        }
        if (couponInfo.getCouponWay()==3&&(couponInfo.getDiscount()>couponInfo.getLowerMoney())){
            return HttpResult.fail("满减金额不能小于优惠金额");
        }
        couponInfoMapper.updateByPrimaryKey(couponInfo);
        return HttpResult.OK;
    }

}
